package com.example.service_msm.controller;

import com.example.commonutils.ResultData;
import com.example.service_msm.service.MsmService;
import com.example.service_msm.utils.RandomUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

//  发送短信的方法
    @GetMapping("send/{phone}")
    public ResultData sendMsm(@PathVariable String phone){
        //先读取redis，如果对应的手机号有值，那么说明验证码已经发送且还未过期，
        //此时为避免重复发送验证码，直接返回成功
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtil.isNullOrEmpty(code)){
            return ResultData.ok();
        }
        //获取4位的随机数
        code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
        //做短信发送
        boolean bool = msmService.send(param,phone);
        //返回true表示发送成功
        if (bool) {
            //发送短信成功，那么就将手机号和验证码作为键值队存入redis并设置5分钟有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return ResultData.ok();
        }else {
            return ResultData.error().message("短信发送失败！");
        }
    }
}
